package com.web.exiaodao.remote.service.impl;

import com.alibaba.fastjson.JSON;
import com.web.exiaodao.business.constant.JConstant;
import com.web.exiaodao.business.entity.User;
import com.web.exiaodao.business.entity.WalletRechargeRecord;
import com.web.exiaodao.business.repository.UserRepository;
import com.web.exiaodao.business.repository.WalletRechargeRecordRepository;
import com.web.exiaodao.remote.service.ApiWalletRechargeRecordService;
import com.web.exiaodao.remote.service.ApiWalletTradeRecordService;
import com.web.exiaodao.remote.vo.WalletRechargeRecordVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.util.DateUtils;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author: zhangl
 * @times: 2017-02-06 10:47:16
 * 类的说明：前端APIWalletRechargeRecord接口实现类
 **/
@Service("ApiWalletRechargeRecordService")
@Transactional(readOnly = false)
public class ApiWalletRechargeRecordServiceImpl extends BaseService<WalletRechargeRecord> implements ApiWalletRechargeRecordService{

	private static final Logger LOGGER = Logger.getLogger(ApiWalletRechargeRecordServiceImpl.class);

	@Autowired
	WalletRechargeRecordRepository walletRechargeRecordRepository;
    @Autowired
    ApiWalletTradeRecordService walletTradeRecordService;
    @Autowired
    UserRepository userRepository;

	@Override
	public XaResult<WalletRechargeRecordVo> findOne(Long tId) throws BusinessException {
		WalletRechargeRecord obj = walletRechargeRecordRepository.findByIdAndStatusNot(tId,XaConstant.Status.delete);
		XaResult<WalletRechargeRecordVo> xr = new XaResult<WalletRechargeRecordVo>();
		if (XaUtil.isNotEmpty(obj)) {
			xr.setObject(JSON.parseObject(JSON.toJSONString(obj),WalletRechargeRecordVo.class));
			xr.getObject().setId(obj.getId());
			LOGGER.info("查询单个实体----->WalletRechargeRecord");
		} else {
			xr.error(XaConstant.Message.object_not_find);
			LOGGER.info(XaConstant.Message.object_not_find);
			throw new BusinessException(XaConstant.Message.object_not_find);
		}
		return xr;
	}

	@Override
	public XaResult<List<WalletRechargeRecordVo>> findListNEStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable)
			throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示非删除的所有数据
			status = XaConstant.Status.delete;
		}
		filters.put("status", new SearchFilter("status", Operator.NE, status));
		Page<WalletRechargeRecord> page = walletRechargeRecordRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), WalletRechargeRecord.class), pageable);
		XaResult<List<WalletRechargeRecordVo>> xr = new XaResult<List<WalletRechargeRecordVo>>();
		xr.setObject(JSON.parseArray(JSON.toJSONString(page.getContent()), WalletRechargeRecordVo.class));
		for(int i=0;i<page.getContent().size();i++){
			xr.getObject().get(i).setId(page.getContent().get(i).getId());
		}
		return xr;
	}

	@Override
	public XaResult<List<WalletRechargeRecordVo>> findListEQStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable)
			throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示正常数据
			status = XaConstant.Status.valid;
		}
		filters.put("status", new SearchFilter("status", Operator.EQ, status));
		Page<WalletRechargeRecord> page = walletRechargeRecordRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), WalletRechargeRecord.class), pageable);
		XaResult<List<WalletRechargeRecordVo>> xr = new XaResult<List<WalletRechargeRecordVo>>();
		xr.setObject(JSON.parseArray(JSON.toJSONString(page.getContent()), WalletRechargeRecordVo.class));
		for(int i=0;i<page.getContent().size();i++){
			xr.getObject().get(i).setId(page.getContent().get(i).getId());
		}
		return xr;
	}

	@Override
	public XaResult<WalletRechargeRecordVo> multiOperate(String modelIds,
			Integer status) throws BusinessException {
		XaResult<WalletRechargeRecordVo> xr = new XaResult<WalletRechargeRecordVo>();
		if(status == null){
			status = XaConstant.Status.delete;
		}
		if(modelIds != null){
			String[] ids = modelIds.split(",");
			for(String id : ids){
				WalletRechargeRecord obj = walletRechargeRecordRepository.findByIdAndStatusNot(Long.parseLong(id),status);
				if (XaUtil.isNotEmpty(obj)) {
					obj.setStatus(status);
					obj = walletRechargeRecordRepository.save(obj);
					xr.setObject(JSON.parseObject(JSON.toJSONString(obj), WalletRechargeRecordVo.class));
					xr.getObject().setId(obj.getId());
				}
			}
		}
		LOGGER.info("更改数据状态----->WalletRechargeRecord");
		return xr;
	}

	@Override
	public XaResult<WalletRechargeRecordVo> createModel(WalletRechargeRecord model)
			throws BusinessException {
		XaResult<WalletRechargeRecordVo> xr = new XaResult<WalletRechargeRecordVo>();

		//1:未充值订单自动关闭
		List<WalletRechargeRecord> list = walletRechargeRecordRepository.findByUserIdAndRechargeStatusAndStatusNot(model.getUserId(), JConstant.WalletRechargeStatus.RECHARGE_ING, XaConstant.Status.delete);
		if (XaUtil.isNotEmpty(list)) {
			for (int i = 0; i < list.size(); ++i) {
				WalletRechargeRecord record = list.get(i);
				record.setRechargeStatus(JConstant.WalletRechargeStatus.RECHARGE_CLOSE);
			}
			walletRechargeRecordRepository.save(list);
		}

        //2:保存
        WalletRechargeRecord obj = walletRechargeRecordRepository.save(model);
        xr.setObject(JSON.parseObject(JSON.toJSONString(obj), WalletRechargeRecordVo.class));
        xr.getObject().setId(obj.getId());

		LOGGER.info("新增数据成功----->WalletRechargeRecord");
		return xr;
	}

	@Override
	public XaResult<WalletRechargeRecordVo> updateModel(WalletRechargeRecord model)
			throws BusinessException {
		WalletRechargeRecord obj = walletRechargeRecordRepository.findOne(model.getId());
		XaResult<WalletRechargeRecordVo> xr = new XaResult<WalletRechargeRecordVo>();
		if (XaUtil.isNotEmpty(obj)) {
					obj.setUserId(XaUtil.isNotEmpty(model.getUserId()) ? model.getUserId() : obj.getUserId());
					obj.setRechargeMoney(XaUtil.isNotEmpty(model.getRechargeMoney()) ? model.getRechargeMoney() : obj.getRechargeMoney());
					obj.setRechargeOrderNo(XaUtil.isNotEmpty(model.getRechargeOrderNo()) ? model.getRechargeOrderNo() : obj.getRechargeOrderNo());
					obj.setRechargeMethod(XaUtil.isNotEmpty(model.getRechargeMethod()) ? model.getRechargeMethod() : obj.getRechargeMethod());
					obj.setRechargeStatus(XaUtil.isNotEmpty(model.getRechargeStatus()) ? model.getRechargeStatus() : obj.getRechargeStatus());
					obj.setQueryId(XaUtil.isNotEmpty(model.getQueryId()) ? model.getQueryId() : obj.getQueryId());
					obj.setOrderPayDateTime(XaUtil.isNotEmpty(model.getOrderPayDateTime()) ? model.getOrderPayDateTime() : obj.getOrderPayDateTime());
				obj = walletRechargeRecordRepository.save(obj);
			xr.setObject(JSON.parseObject(JSON.toJSONString(obj), WalletRechargeRecordVo.class));
			xr.getObject().setId(obj.getId());
		} else {
			xr.error(XaConstant.Message.object_not_find);
		}
		LOGGER.info("编辑数据成功----->WalletRechargeRecord");
		return xr;
	}

	//支付成功后处理充值订单状态
	@Override
	public String modifyRechargeOrder(String orderNo, String price, String queryId, int payType) throws BusinessException {
		WalletRechargeRecord order = walletRechargeRecordRepository.findByRechargeOrderNoAndStatusNot(orderNo,
				XaConstant.Status.delete);
		if (XaUtil.isNotEmpty(order) && order.getRechargeStatus().intValue() == JConstant.WalletRechargeStatus.RECHARGE_SUCESS) {//已经支付
			return "0001"; // 0001代表已经支付过
		}
		try {
			order.setRechargeMethod(payType);
			if (XaUtil.isNotEmpty(order) && order.getRechargeStatus().intValue() == JConstant.WalletRechargeStatus.RECHARGE_ING) {//未支付
                order.setRechargeStatus(JConstant.WalletRechargeStatus.RECHARGE_SUCESS);
                order.setQueryId(queryId);
                order.setOrderPayDateTime(DateUtils.getStrDate(new Date(), DateUtils.YYYYMMDDHHMMSS));
                walletRechargeRecordRepository.save(order);

                User user = userRepository.findById(order.getUserId());
                //保存交易记录

                walletTradeRecordService.rechargeSucessSaveRecord(XaUtil.getNutNullDouble(price,0), user, order);
            }
			return "0000"; // 支付成功后状态修改成功
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
			return "0002"; // 支付成功后状态修改失败
		}
	}
}
